package info.qingshui.browser.hk.file;

import java.io.*;
import java.io.UnsupportedEncodingException;

import java.io.IOException;

import android.content.Context;
import android.util.*;

public class FileManager {
	private static FileManager fileManager = null;
	private Context context;
	private String filePath;//私有存储文件目录
	

	private FileManager(Context context) {
		this.context = context;
		//SDPATH = Environment.getExternalStorageDirectory().getPath() + "/";
		filePath = this.context.getFilesDir().getPath()+ "/" ;
	}
	
	public static FileManager getFileManager(Context context) {
		if ( fileManager == null ) {
			fileManager = new FileManager( context );
		}
		return fileManager;
	}
	

	

	
	public String getFilePath() {
		return filePath;
	}

	/**
	 * 将assets下某目录所有文件copy 到私有存储destDir目录下,destDir目录不存在自动生成
	 * @param assetPath  pathname/pathname , pathname
	 * @param destDir pathname/pathname , pathname
	 * @return
	 * @throws IOException
	 */
	public boolean copyAssetFilesTo(String assetPath, String destDir){
		
		String[] files;
		try {
			files = context.getAssets().list(assetPath);
			File destPath = new File( filePath + "/" + destDir +"/");
			if ( !destPath.exists() ) {
				destPath.mkdirs();
			}
			for( String file: files ) {
				
				InputStream is =  context.getAssets().open(assetPath + "/"+ file) ;
				File destfile = new File( filePath + "/" + destDir +"/"+ file);
				Log.d(FileManager.class.getSimpleName(), "copy file=" + assetPath + "/"+ file +  " to " + destfile.getAbsolutePath());
				FileOutputStream fos = new FileOutputStream( destfile);
				int readLen = 0;
				byte[] buf = new byte[1024];
				while ((readLen = is.read(buf)) != -1) {
					fos.write(buf, 0, readLen);
					Log.d(FileManager.class.getSimpleName(), "copyAssetFilesTo writs:" + readLen );
				}
				fos.flush();
				fos.close();
				is.close();
			}
			return true;
		} catch (Exception e) {
			Log.e(FileManager.class.getSimpleName(), "copyAssetFilesTo error" ,e);
		}
		return false;
	}
	
	/**
	 * 所有文本文件为UTF-8编码
	 * @param fileName  assets目录下的相对路径，如index/index.html, ulrs.txt
	 * @return
	 */
	public BufferedReader openAssetReader(String fileName) throws IOException {
		try {
			return new BufferedReader (new InputStreamReader( context.getAssets().open( fileName ),"UTF-8") );
		} catch (UnsupportedEncodingException e) {
			Log.w(FileManager.class.getSimpleName(), "openAssetReader warn" ,e);
			return new BufferedReader (new InputStreamReader( context.getAssets().open( fileName )) );
		} 
	
	}


	

}
